package com.cgbl.cg.vm.mine

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import api.CourseServiceFactory
import api.ResourceServiceFactory
import api.ShopServiceFactory
import com.alibaba.fastjson.JSON
import com.cgbl.cg.utils.city.BeanTransferHelper
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.CommentBean
import com.robot.base.model.PageListBean
import com.robot.base.model.ResourceDetailBean
import com.robot.base.util.ToastUtils
import com.robot.base.util.arouter.ARouterUtil
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class ResourceProfileViewModel(application: Application) : GLBaseViewModel(application) {
    val courseLogo = ObservableField<String>()
    var productId = ""

    var accountId = ""

    val uc = UiChangeEvent()

    val tabType = ObservableInt(TAB_PROFILE)

    var isCollectionField = ObservableBoolean(false)

    var isBuyField = ObservableBoolean(false)

    var commentTagField = ObservableField<String>()

    var bottomLeftBtn = ObservableField("加入购物车")

    var bottomRightBtn = ObservableField("立即购买")

    var id = ""

    val clickFullScreenCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Main.A_VIDEO)
    })
    val addCartCommand = BindingCommand<Any>(BindingAction {
        if(isBuyField.get()){
            //查看购物车
            ARouterUtil.goToActivity(AppConstants.Router.Mine.A_MINE_SHOPPING_CAR)
            return@BindingAction
        }
        doAddCart()
    })

    val buyCommand = BindingCommand<Any>(BindingAction {
        if(isBuyField.get()){
            return@BindingAction
        }
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("商品为空!")
            return@BindingAction
        }
        ARouterUtil.goToActivityWithBundle(
            AppConstants.Router.Mine.A_MINE_CONFIRM_ORDER,
            Bundle().apply {
                putString(
                    AppConstants.BundleKey.SHOP_CART_BEAN, JSON.toJSONString(
                        BeanTransferHelper.createConfirmOrderProductByCourse(productId, "2")
                    )
                )
            })
    })

    val addCollectionCommand = BindingCommand<Any>(BindingAction {
        doCollection()
    })

    val toCommentProfileCommand = BindingCommand<Any>(BindingAction {
        toComment()
    })

    val clickSelectProfileCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_PROFILE)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickSelectDirectoryCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_DIRECTORY)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickSelectCommentCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_COMMENT)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickSelectFileCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_FILE)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickShoppingCarCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Mine.A_MINE_SHOPPING_CAR)
    })

    val userAvatar = ObservableField<String>()

    var page = 1

    var pageSize = 10

    init {
        userAvatar.set("https://ep.watsons.com.cn/MPOSImage/3456_sco_home_pic.png")
    }

    class UiChangeEvent {

        val switchTabEvent: SingleLiveEvent<Int> = SingleLiveEvent()

        val resourceInfoData: SingleLiveEvent<ResourceDetailBean> = SingleLiveEvent()

        val refreshCommentEvent: SingleLiveEvent<List<CommentBean>> = SingleLiveEvent()

        val loadMoreCommentEvent: SingleLiveEvent<List<CommentBean>> = SingleLiveEvent()

    }

    fun refresh() {
        page = 1
        fetchCourseComment(productId)
    }

    fun loadMore() {
        page++
        fetchCourseComment(productId)
    }

    fun fetchResourceInfo(id: String) {
        productId = id
        ResourceServiceFactory.getNaturalInfo(id)
            .subscribe(object :
                AbstractViewModelSubscriber<BaseResponse<ResourceDetailBean>>(this) {
                override fun onNext(t: BaseResponse<ResourceDetailBean>) {
                    courseLogo.set(t.data.courseLogo)
                    accountId = t.data.accountId ?: ""
                    uc.resourceInfoData.postValue(t.data)
                    isCollectionField.set(t.data.collectType == "1")
                    commentTagField.set("评价（${t.data.comentCount}）")
                    val ispay = t.data.pay
                    isBuyField.set(t.data.pay == "1")
                    bottomLeftBtn.set(if(isBuyField.get()) "查看购物车" else " 加入购物车")
                    bottomRightBtn.set(if(isBuyField.get()) "已购买" else " 立即购买")
                }
            })
    }

    fun fetchCourseComment(id: String) {
        productId = id
        val params = mapOf(
            "allOff" to "1",
            "type" to "0",
            "naturalId" to id,
            "pageNo" to page,
            "pageSize" to pageSize
        )
        ResourceServiceFactory.pageComment(params).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CommentBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CommentBean>>) {
                if (page == 1) {
                    uc.refreshCommentEvent.postValue(t.data.list)
                } else {
                    uc.loadMoreCommentEvent.postValue(t.data.list)
                }
            }
        })
    }

    private fun toComment() {
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("商品id不能为空！")
            return
        }
        ARouterUtil.goToActivityWithBundle(
            AppConstants.Router.Mine.A_MINE_COMMENT_PROFILE,
            Bundle().apply {
                putInt(
                    AppConstants.BundleKey.COMMENT_PRODUCT_TYPE,
                    AppConstants.BundleValue.COMMENT_TYPE_RESOURCE
                )
                putString(AppConstants.BundleKey.COMMENT_PRODUCT_ID, productId)
                putString(AppConstants.BundleKey.COMMENT_PARENT_ID, "0")
                putString(AppConstants.BundleKey.COMMENT_ACCOUNT_ID, accountId)
            })
    }

    private fun doAddCart() {
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("添加失败,商品id不能为空！")
            return
        }
        val params = mapOf("productId" to productId, "type" to "1")

        ShopServiceFactory.cartCreate(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort("添加成功!")
                }
            })
    }

    private fun doCollection() {
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("添加失败,商品id不能为空！")
            return
        }
        val collectType = if (isCollectionField.get()) {
            "0"
        } else {
            "1"
        }
        val params = mapOf("courseId" to productId, "type" to collectType)

        ResourceServiceFactory.saveCollectNatural(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
                override fun onNext(t: BaseResponse<String>) {
                    ToastUtils.showShort(if (collectType == "0") "取消收藏!" else "收藏成功!")
                    isCollectionField.set(collectType == "1")
                }
            })
    }

    fun likeComment(id: String, success: (uploadBean: String) -> Unit){
        ResourceServiceFactory.createCommentLike(
            mapOf(
                "commentId" to id
            )
        ).subscribe(object :AbstractViewModelSubscriber<BaseResponse<String>>(this){
            override fun onNext(t: BaseResponse<String>) {
                success.invoke(t.data)
            }
        })
    }
    companion object {

        const val TAB_PROFILE = 1

        const val TAB_DIRECTORY = 2

        const val TAB_COMMENT = 3

        const val TAB_FILE = 4

    }
}